package com.magicode.screen.share;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.magicode.screen.AppConfig;
import com.magicode.screen.R;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.wxapi.WXUtil;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *需要分享一些长图，大图到微信，微博等。
 * 由于微信微博自己的官方sdk对图片有限制，
 * 比如微博要求缩略图不能大于32k,原图不能大于2M.
 * 所以直接调用安卓系统自带的分享功能
 * Created by dell on 2017/6/12.
 */
public class IntentShareUtil{
    /**
     * sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
     * sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
     * sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
     * sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
     * sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
     * sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
     **/
    private final String WEIXIN_PACKAGENAME="com.tencent.mm";
    private final String QQ_PACKAGENAME="com.tencent.mobileqq";
    private final String WEIBO_PACKAGENAME="com.sina.weibo";
    private final String qzone_PACKAGENAME="com.qzone";
    private final String FILEPROVIDER="com.magicode.screen.fileprovider";
    private  String imagePath=Environment.getExternalStorageDirectory() + File.separator+"/Pictures/" ;//huxiu  +"/Pictures/screen.jpg"
    private  Context context;
    /**
     * 分享
     */
    public Boolean  handleImageShare(Context contextshare ,String  fileName, String type) {
        try {

            if (null != fileName && !"".equals(fileName) && null != type && !"".equals(type)) {
                imagePath =imagePath+fileName;
                this.context=contextshare;
                switch (type) {
                    case "circle":
                        if (checkInstallation(context, WEIXIN_PACKAGENAME)) {
//                            WXCircle(context);//朋友圈
                            imageShare(imagePath,1);
                        } else {
                            Toast.makeText(context, "您还暂未安装微信", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "weixin":
                        if (checkInstallation(context, WEIXIN_PACKAGENAME)) {
//                            WXfrinds(context);//微信
                            imageShare(imagePath,0);
                        } else {
                            Toast.makeText(context, "您还暂未安装微信", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "weibo":
                        if (checkInstallation(context, WEIBO_PACKAGENAME)) {
                            showSinaDialog(context);
                        } else {
                            Toast.makeText(context, "您还暂未安装微博", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "qq":
                        if (checkInstallation(context, QQ_PACKAGENAME)) {
//                            qq(context);
                            ShareQQ(context);
                        } else {
                            Toast.makeText(context, "您还暂未安装QQ", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "qzone":
                        if (checkInstallation(context, QQ_PACKAGENAME)) {
//                            qzone(context);
                            ShareQQzone(context);
                        } else {
                            Toast.makeText(context, "您还暂未安装QQ", Toast.LENGTH_LONG).show();
                        }
                        break;
                    case "more":
                        this.showSystemShareOption(context);
                        break;
                    default:
                        break;
                }
            }
            return true;
        }catch (Exception e){
            return  false;
        }

    }

    /**
     * 判断是否安装腾讯、新浪等指定的分享应用
     * @param packageName 应用的包名
     */
    public boolean checkInstallation(Context context,String packageName){
        try {
            context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName
     *            ：应用包名
     * @return
     */
    private boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public void WXCircle(final Context context){
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "huxiu.jpg";
        //由文件得到uri
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }
        final Intent shareIntent = new Intent();
        //发送图片到朋友圈
        ComponentName comp = new ComponentName(WEIXIN_PACKAGENAME, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(shareIntent);

    }
    public void WXfrinds(final Context context){
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator +"huxiu.jpg";

        //由文件得到uri
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }

        final Intent shareIntent = new Intent();
        //发送图片给好友。
        ComponentName comp = new ComponentName(WEIXIN_PACKAGENAME, "com.tencent.mm.ui.tools.ShareImgUI");
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(shareIntent);

    }
    public void qq(final Context context){
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "huxiu.jpg";
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }

        final Intent shareIntent = new Intent();
        //发送图片到qq
        ComponentName comp = new ComponentName(QQ_PACKAGENAME, "com.tencent.mobileqq.activity.JumpActivity");
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
//        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shareIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        context.startActivity(shareIntent);

    }
    public void qzone(final Context context){
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "huxiu.jpg";
        //由文件得到uri
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }
        final Intent shareIntent = new Intent();
        //发送图片到qq
        ComponentName comp = new ComponentName(qzone_PACKAGENAME, "com.qzonex.module.operation.ui.QZonePublishMoodActivity");
        shareIntent.setComponent(comp);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(shareIntent);

    }
    private void ShareQQ(final Context context) {
        Tencent mTencent = Tencent.createInstance(Constants.QQ_APPID, context);
        if (mTencent.isSessionValid() && mTencent.getOpenId() == null) {
            Toast.makeText(context, "没有安装QQ,请先安装QQ!", Toast.LENGTH_SHORT).show();
        }
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,imagePath);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.getString(R.string.app_name));
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        mTencent.shareToQQ((Activity) context, params, qqShareListener);
    }
    private void ShareQQzone(final Context context) {
        Tencent mTencent = Tencent.createInstance(Constants.QQ_APPID, context);
        if (mTencent.isSessionValid() && mTencent.getOpenId() == null) {
            Toast.makeText(context, "没有安装QQ,请先安装QQ!", Toast.LENGTH_SHORT).show();
        }
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,imagePath);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.getString(R.string.app_name));
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        mTencent.shareToQQ((Activity) context, params, qqShareListener);
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            Toast.makeText(context, "发送取消 ", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "发送成功 ", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "发送失败 ", Toast.LENGTH_LONG).show();
        }
    };
    public void showSinaDialog(final Context context) {
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "huxiu.jpg";
        //由文件得到uri
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }
        final Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        PackageManager pm =context.getPackageManager();
        List<ResolveInfo> matches = pm.queryIntentActivities(shareIntent, PackageManager.MATCH_DEFAULT_ONLY);
        String packageName = WEIBO_PACKAGENAME;
        ResolveInfo info = null;
        for (ResolveInfo each : matches) {
            String pkgName = each.activityInfo.applicationInfo.packageName;
            if (packageName.equals(pkgName)) {
                info = each;
                break;
            }
        }
        if (info == null) {
//            new AlertDialog.Builder(context)
//                    .setTitle("提示")
//                    .setMessage("您还没有安装新浪微博，是否前往浏览器下载？")
//                    .setPositiveButton("确定",
//                            new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog,
//                                                    int which) {
//                                    Uri uri = Uri
//                                            .parse("http://app.sina.cn/appdetail.php?appID=84560");
//                                    Intent intent = new Intent(
//                                            Intent.ACTION_VIEW, uri);
//                                    context.startActivity(intent);
//                                    dialog.dismiss();
//                                }
//                            })
//                    .setNegativeButton("取消",
//                            new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog,
//                                                    int which) {
//                                    // TODO Auto-generated method stub
//                                    dialog.dismiss();
//                                }
//                            }).show();
        } else {
            shareIntent.setClassName(packageName, info.activityInfo.name);
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(shareIntent);

    }
    /**
     * 微信分享
     */
    private IWXAPI api;

    public void imageShare(String imgurl,int sendtype){
        if (api == null) {
            api = WXAPIFactory.createWXAPI(this.context, AppConfig.APP_WX_KEY, false);
            api.registerApp(AppConfig.APP_WX_KEY);
        }
        if (!api.isWXAppInstalled()) {
            //提醒用户没有按照微信
            Toast.makeText(this.context, "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
            return;
        }

        File file = new File(imgurl);
        if (!file.exists()) {

            Toast.makeText(context, "图片不存在", Toast.LENGTH_LONG).show();

        }
        WXImageObject imgObj = new WXImageObject();
        imgObj.setImagePath(imgurl);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap bmp = BitmapFactory.decodeFile(imgurl);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 120, 120, true);
        msg.setThumbImage(thumbBmp);
        bmp.recycle();
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = sendtype==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }
    /**
     * 图片类型
     * @param flag
     */
    private void shareImageToWx(final int flag) {
        Bitmap bmp=BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_screen);
        //初始化
        WXImageObject imgObj=new WXImageObject(bmp);
        WXMediaMessage msg=new WXMediaMessage();
        msg.mediaObject=imgObj;
        //设置缩略图
        Bitmap thumbBmp=Bitmap.createScaledBitmap(bmp,120,120,true);
        bmp.recycle();
        msg.thumbData= WXUtil.bmpToByteArray(thumbBmp,true);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction= buildTransaction("img");//transaction 字段用于唯一表示一个请求
        req.message=msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    /**
     * 调用系统安装了的应用分享
     *
     * @param context
     */
    public  void showSystemShareOption(final Context context) {
//        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "huxiu.jpg";
        //由文件得到uri
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri =  FileProvider.getUriForFile(context, FILEPROVIDER, new File(imagePath));
        } else {
            imageUri = Uri.fromFile(new File(imagePath));
        }
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        // 遍历所有支持发送图片的应用。找到需要的应用
//        PackageManager pm =context.getPackageManager();
//        List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
//        ComponentName componentName = null;
//        for (int i = 0; i < resolveInfoList.size(); i++) {
//            if (TextUtils.equals(
//                    resolveInfoList.get(i).activityInfo.packageName, "com.tencent.mobileqq")) {
//                String packageName= resolveInfoList.get(i).activityInfo.packageName;
//                String name=  resolveInfoList.get(i).activityInfo.name;
//                componentName = new ComponentName(
//                        resolveInfoList.get(i).activityInfo.packageName,
//                        resolveInfoList.get(i).activityInfo.name);
//                break;
//            }
//        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    }

    /*
     * 压缩图片，避免内存不足报错
     */
    private Bitmap decodeFile(File f) {
        Bitmap b = null;
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            FileInputStream fis = new FileInputStream(f);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();

            int scale = 1;
            if (o.outHeight > 100 || o.outWidth > 100) {
                scale = (int) Math.pow(
                        2,
                        (int) Math.round(Math.log(100 / (double) Math.max(
                                o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            fis = new FileInputStream(f);
            b = BitmapFactory.decodeStream(fis, null, o2);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }

}
